package cn.xorange.commons.security.provider;

import cn.xorange.commons.security.entity.SecurityUser;
import cn.xorange.commons.security.service.UserDetailsServiceImpl;
import cn.xorange.commons.security.token.CustomAuthToken;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author : yangjian
 * @date : 2023/11/25
 */
@Component
public class CustomAuthProvider implements AuthenticationProvider {

    @Resource
    private UserDetailsServiceImpl userDetailsService;



    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        CustomAuthToken token = (CustomAuthToken)authentication;
        JSONObject object = (JSONObject) token.getDetails();

        SecurityUser userDetails = userDetailsService.loadUserByUsername(object);

        CustomAuthToken authToken = new CustomAuthToken(token.getPrincipal(), token.getAuthorities());
        authToken.setDetails(userDetails);

        return authToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        /**
         * providerManager会遍历所有
         * securityConfig中注册的provider集合
         * 根据此方法返回true或false来决定由哪个provider
         * 去校验请求过来的authentication
         */
        return CustomAuthToken.class.isAssignableFrom(authentication);
    }




}
